package com.Indb.util;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class JdbcUtils {
    //数据库驱动权限定类名，不需要改动
    private static String DRIVER;
    //数据库链接URL
    private static String URL;
    //数据库链接用户名
    private static String USERNAME;
    //数据库链接密码
    private static String PASSWORD;
    private static String filename = "/app.properties";

    static {
        Properties properties = new Properties();
        try {
            //加载文件流
            properties.load(JdbcUtils.class.getResourceAsStream(filename));
            //将配置文件中的属性全部读出来 并且赋值到当前类成员变量中
            DRIVER = properties.getProperty("DRIVER");
            URL = properties.getProperty("URL");
            USERNAME = properties.getProperty("USERNAME");
            PASSWORD = properties.getProperty("PASSWORD");
            System.out.println();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //数据库驱动加载
        //1.注册驱动
        //Java类加载机制， 加载com.mysql.jdbc.Driver
        try {
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            System.out.println("全类名" + DRIVER + "没有找到");
        }
    }

    public static Connection getConnection() {
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }
}
